package com.app.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
public class LoginfailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        Map<String, Object> results = new HashMap<String,Object>();
        //具体返回结果
        if(exception instanceof BadCredentialsException){
            results.put("code", 201);
            results.put("message", "用户名或密码错误！");
            results.put("data", null);
        }else{
            exception.printStackTrace();
            results.put("code", 500);
            results.put("message", exception.getMessage());
        }
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().print(new ObjectMapper().writeValueAsString(results));

    }
}
